package flc.ast.fragment;

import android.Manifest;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.util.Log;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.weather.lib.WeatherManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.BuyCostActivity;
import flc.ast.activity.GasStationActivity;
import flc.ast.activity.InstructionActivity;
import flc.ast.activity.ParkActivity;
import flc.ast.adapter.OilAdapter;
import flc.ast.bean.MyOilBean;
import flc.ast.databinding.FragmentHomeBinding;
import stark.common.apis.ApiManager;
import stark.common.apis.base.GnyjBean;
import stark.common.apis.base.Weather;
import stark.common.base.IReqRetCallback;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.LocationUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> {

    private String weather = "", fs, temperature, province;
    private int selMarkPos = 0;
    private boolean isLocation = false;//是否获取定位
    private List<MyOilBean> listOil = new ArrayList<>();
    private OilAdapter oilAdapter;

    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);
        mDataBinding.rvOilList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        oilAdapter = new OilAdapter();
        mDataBinding.rvOilList.setAdapter(oilAdapter);
        mDataBinding.ivInstruction.setOnClickListener(this);
        mDataBinding.ivBuyCarCost.setOnClickListener(this);
        mDataBinding.ivFindPark.setOnClickListener(this);
        mDataBinding.ivGasStation.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivInstruction:
                startActivity(InstructionActivity.class);
                break;
            case R.id.ivBuyCarCost:
                startActivity(BuyCostActivity.class);
                break;
            case R.id.ivFindPark:
                goPark();
                break;
            case R.id.ivGasStation:
                goGasStation();
                break;
        }
    }

    @Override
    protected void initData() {
        //初始化定位天气
        WeatherManager.initCityData(new WeatherManager.IInitCallback() {
            @Override
            public void onRet(boolean success) {
                if (!success) return;
                getPermission();
            }
        });
    }

    private void goPark() {
        StkPermissionHelper.permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .reqPermissionDesc(getString(R.string.get_park_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        startActivity(ParkActivity.class);
                    }
                }).request();
    }

    private void goGasStation() {
        StkPermissionHelper.permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .reqPermissionDesc(getString(R.string.get_gas_station_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        startActivity(GasStationActivity.class);
                    }
                }).request();
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .reqPermissionDesc(getString(R.string.get_location_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        //初始化定位天气
                        getWeatherByMap();
                    }
                }).request();
    }

    //判断权限
    private void getWeatherByMap() {
        boolean isEnabled = LocationUtil.isLocationEnabled();
        if (!isEnabled) {
            ToastUtils.showShort(R.string.please_open_location);
            return;
        }
        startLoc();
    }

    //开始定位
    private AMapLocationClient client;

    private void startLoc() {
        if (client != null) {
            return;
        }
        showDialog(getString(R.string.get_location_ing));
        client = new AMapLocationClient(mContext);
        AMapLocationClientOption clientOption = new AMapLocationClientOption();
        clientOption.setInterval(3000);
        clientOption.setNeedAddress(true);
        client.setLocationOption(clientOption);
        client.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation == null) return;
                int errCode = aMapLocation.getErrorCode();
                if (errCode != 0) return;
                String city = aMapLocation.getCity();
                province = aMapLocation.getProvince();
                //根据城市名称来获取天气信息
                getWeather(aMapLocation.getCity());
                //根据省份获取油价
                getOil();
                mDataBinding.tvCity.setText(city);
                dismissDialog();
            }
        });
        client.startLocation();
    }

    //停止获取定位
    private void stopLoc() {
        if (client != null) {
            client.stopLocation();
            client.onDestroy();
            client = null;
        }
    }

    //获取天气
    private void getWeather(String city) {
        WeatherManager.getWeather(this, city, new IReqRetCallback<Weather>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable Weather result) {
                if (success && result != null) {
                    weather = result.future.get(0).weather;//获取当天天气
                    temperature = result.realtime.temperature;
                    fs = result.future.get(0).direct;
                    mDataBinding.tvWeather.setText(weather + result.future.get(0).temperature);
                    mDataBinding.tvWeatherFs.setText(fs);
                    mDataBinding.tvTemp.setText(temperature);
                    if (weather.equals("晴")) {
                        mDataBinding.ivWeatherImg.setImageResource(R.drawable.qingtian1);
                    } else if (weather.equals("多云")) {
                        mDataBinding.ivWeatherImg.setImageResource(R.drawable.duoyun1);
                    } else if (weather.equals("阴")) {
                        mDataBinding.ivWeatherImg.setImageResource(R.drawable.yintian1);
                    } else if (weather.contains("雨")) {
                        mDataBinding.ivWeatherImg.setImageResource(R.drawable.yutian1);
                    } else if (weather.contains("雪")) {
                        mDataBinding.ivWeatherImg.setImageResource(R.drawable.xuetian1);
                    }
                }
            }
        });
    }

    private void getOil() {
        ApiManager.toolKitApi().gnyjQuery(this, new IReqRetCallback<List<GnyjBean>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<GnyjBean> result) {
                if (success) {
                    listOil.clear();
                    for (GnyjBean gnyjBean : result) {
                        if (province.contains(gnyjBean.city)) {
                            listOil.add(new MyOilBean(gnyjBean.h0, "柴油", "0#"));
                            listOil.add(new MyOilBean(gnyjBean.h98, "汽油", "98#"));
                            listOil.add(new MyOilBean(gnyjBean.h95, "汽油", "95#"));
                            listOil.add(new MyOilBean(gnyjBean.h92, "汽油", "92#"));
                            oilAdapter.setList(listOil);
                        }
                    }
                }
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLoc();
    }

}